package name.sra.util;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

public class ImageLine {

	public static long count = 0;
	public static long finalizeCount = 0;
	
	private BufferedImage inputImage;
	private BufferedImage outputImage;
	private int lineRow;
	private int lineBegin;
	private int lineEnd;
	private List<ImageLine> contiguousLines;
	
	public ImageLine(BufferedImage anIput, BufferedImage anOutput, int row, int begin, int end) {
		count++;
		this.inputImage = anIput;
		this.outputImage = anOutput;
		this.lineRow = row;
		this.lineBegin = begin;
		this.lineEnd = end;
		this.contiguousLines = new ArrayList<ImageLine>();
	}
	
	public ImageLine(BufferedImage anIput, BufferedImage anOutput, int row) {
		this(anIput, anOutput, row, 0, anIput.getWidth() - 1);
	}

	public void calculateContiguousLines(double level) {
		int rgb = inputImage.getRGB(0, lineRow);
		int begin = 0;
		int index =1;
		contiguousLines = new ArrayList<ImageLine>();
		boolean previousIsOver = isOverLevel(level, rgb);
		
		while (index < getLength()) {
			rgb = inputImage.getRGB(index, lineRow);
			boolean isOver = isOverLevel(level, rgb);
			if (isOver != previousIsOver) {
				if (!isOver) {
					ImageLine line = new ImageLine(inputImage, outputImage, lineRow, begin, index - 1);
					contiguousLines.add(line);
				}
				begin = index;
				previousIsOver = isOver;
			}
			index++;
		}
		if (isOverLevel(level, rgb)) {
			ImageLine lastLine = new ImageLine(inputImage, outputImage, lineRow, begin, getLength() - 1);
			contiguousLines.add(lastLine);
		}
	}

	private boolean isOverLevel(double level, int rgb) {
		 return (RgbUtils.calculateIntensity(rgb) < level);
	}
	
	public boolean horizontallyOverlaps(ImageLine other) {
		return !(((other.getLineEnd() < this.getLineBegin())
					|| (other.getLineBegin() > this.getLineEnd() )));
	}
	
	public List<ImageLine> getContiguousLines() {
		return contiguousLines;
	}
	
	public int getLength() {
		return lineEnd - lineBegin + 1;
	}

	public int getLineBegin() {
		return lineBegin;
	}

	public int getLineEnd() {
		return lineEnd;
	}
	
	public void colorize(int rgb) {
		for (int x = 0; x < getLength(); x++) {
			outputImage.setRGB(x + getLineBegin(), lineRow, rgb);
		}
	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		finalizeCount++;
	}
	
	
}
